<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <SmForm
      class="-mb-15px"
      ref="formRef"
      isCol
      label-width="150px"
      v-model="formData"
      v-loading="formLoading"
      :options="requestFormOptions"
      :getModelValue="getFormData"
    >
      <template #avatar>
        <MultiImageUpload
          v-model="formData.imgList1"
          :limit="1"
          @update:model-value="(val) => changeOneImg(val, formData, 'avatar')"
        />
      </template>
    </SmForm>

    <template #footer>
      <el-button @click="submitFormDB" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { createUser, getRoleList, getUser, updateUser } from "@/api/user";
import { addProperty } from "@/components/SmForm/src/utils";
import { createDBFn } from "@/utils/decorate";
import { defaultProps } from "@/utils/tree";
import { getDeptList, getOrganizationList, getUserList } from "@/commonData";
import { phoneRules } from "@/commonData/rules";
import {
  bankAccountTypeList,
  genderList,
  salespersonStatusList,
  userTypeList,
} from "@/commonData/dict";
import { changeOneImg } from "@/utils/changeData";
import SalespersonsAPI from "@/api/sales-manage/salespersons";
import { createInputList } from "@/utils/form";

/** 仓库 表单 */
defineOptions({ name: "OpenForm" });

const { t } = useI18n(); // 国际化

const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref(""); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(""); // 表单的类型：create - 新增；update - 修改
const initFormData = () => {
  return {};
};
const formData: any = ref(initFormData());
const formRef = ref(); // 表单 Ref
const organizationList = ref([]);
const deptList = ref([]);
const roleList = ref([]);
const userList = ref([]);

const requestFormOptions: any = ref([]);

// 银行账户可能要调用银行账户接口
const createRequestFormOptions = () => {
  /**
   * 1-avatar
   * 2-bankAccountName-账户名称
   * 3-bankAccountType-银行账户类型 0:个人账户,1:企业账户
   * 4-bankName-银行账号
   * 5-costAdjustmentRate-动态补偿率-number
   * 6-freezingCommission-number-锁定佣金
   - 7-gender-性别 0:男,1:女* 
     8-idCardNo-身份证号
     9-mobile-手机号
     10-name-姓名
     11-orgNo-机构编号
     12-password-密码
     13-recommenderUserId-推荐人id
     14-remainingCommission-number-剩余佣金
     15-remark-备注
     16-status-状态 0:待审核，1:未通过审核，2:通过审核
     17-userId-用户id
   */
  const list = createInputList([
    { prop: "bankAccountName", label: "账户名称" },
    {
      prop: "bankAccountType",
      type: "select",
      data: bankAccountTypeList,
      label: "银行账户类型",
    },
    { prop: "bankName", label: "银行名称" },
    { type: "input-number", prop: "costAdjustmentRate", label: "动态补偿率" },
    { type: "input-number", prop: "freezingCommission", label: "锁定佣金" },
    { type: "input-number", prop: "remainingCommission", label: "剩余佣金" },
    { type: "select", data: genderList, prop: "gender", label: "性别" },
    { prop: "idCardNo", label: "身份证号" },
    { prop: "mobile", label: "手机号" },
    { prop: "name", label: "姓名" },
    { prop: "password", label: "密码" },
    { type: "tree-select", data: organizationList, prop: "orgNo", label: "机构编号" },

    { type: "select", data: userList, prop: "userId", label: "用户" },
    { type: "select", data: userList, prop: "recommenderUserId", label: "推荐人" },
    //

    { type: "select", data: salespersonStatusList, prop: "status", label: "状态" },
    { prop: "remark", label: "备注" },
  ]);

  addProperty(list);
  return list;
};
requestFormOptions.value = createRequestFormOptions();

/** 打开弹窗 */
const open = async (type: string, userId?: string) => {
  dialogVisible.value = true;
  dialogTitle.value = t("action." + type);
  formType.value = type;
  resetForm();
  getOrganizationList(organizationList);
  getDeptList(deptList);
  getRoleList(roleList);
  getUserList(userList);
  // 修改时，设置数据
  if (userId) {
    formLoading.value = true;
    try {
      formData.value = await SalespersonsAPI.getInfo(userId);
      // 主动触发表单数据回显
      formRef.value.initForm();
    } finally {
      formLoading.value = false;
    }
  }
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(["success"]); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as any;
    if (formType.value === "create") {
      await SalespersonsAPI.create(data);
    } else if (formType.value === "update") {
      await SalespersonsAPI.update(data.userId, data);
    }
    ElMessage.success("操作成功");
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit("success");
  } finally {
    formLoading.value = false;
  }
};
const submitFormDB = createDBFn(submitForm);

/** 重置表单 */
const resetForm = () => {
  formData.value = initFormData();
  formRef.value?.resetFields();
};

const getFormData = () => {
  return formData.value;
};
</script>
